package top.bulk.sse.controller;

import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.mvc.method.annotation.SseEmitter;
import top.bulk.sse.dto.CommonSseParam;
import top.bulk.sse.service.SseEmitterService;

import javax.annotation.Resource;

/**
 * sse 通信 控制层
 *
 * @author 散装java
 * @date 2024-09-10
 */
@RestController
public class SseEmitterController {
    @Resource
    private SseEmitterService sseEmitterService;

    /**
     * 创建sse连接
     **/
    @GetMapping("/sse/createConnect")
    public SseEmitter createConnect(@RequestParam("clientId") String clientId,
                                    @RequestParam("loginId") String loginId,
                                    @RequestParam(required = false) Boolean setHeartBeat) {
        return sseEmitterService.createSseConnect(clientId, loginId, setHeartBeat);
    }

    @PostMapping(value = "/sse/chat", produces = MediaType.TEXT_EVENT_STREAM_VALUE)
    public SseEmitter createConnect(@RequestBody CommonSseParam param) {
        return sseEmitterService.chat(param);
    }

    /**
     * 关闭sse连接
     **/
    @GetMapping("/sse/closeSseConnect")
    public void closeSseConnect(String clientId) {
        sseEmitterService.closeSseConnect(clientId);
    }

    /**
     * 推送消息到所有客户端
     **/
    @PostMapping("/sse/broadcast")
    public void sendMessageToAllClient(String msg) {
        sseEmitterService.sendMessageToAllClient(msg);
    }

    /**
     * 根据clientId发送消息给某一客户端
     **/
    @PostMapping("/sse/sendMessage")
    public void sendMessageToOneClient(String clientId, String msg) {
        sseEmitterService.sendMessageToOneClient(clientId, msg);
    }
}
